package com.erp.module.YuliaoPrint

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import android.widget.AdapterView
import com.erp.bean.YuliaoPrintBean
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.YuliaoPrintAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.util.Dialogutil
import com.erp.util.Myutil
import com.erp.view.PullToRefreshView
import com.example.tsc.tscdll_test.TSCActivity
import kotlinx.android.synthetic.main.fragmengt_yuliao_print.*
import android.graphics.Typeface
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.erp.Myapp
import com.erp.R
import com.erp.module.YuliaoPrint.DayinYuliaoActivity.DayinYuliaoActivity
import com.erp.util.LanYaUtil
import kotlinx.android.synthetic.main.dialog_lanya_shezhi.*
import kotlinx.android.synthetic.main.dialog_lanya_shezhi1.SpLanYa


class  FragmengtYuliaoPrintLabel : BaseKFragment(), YuliaoPrintContract.YuliaoPrintView, AdapterView.OnItemClickListener, PullToRefreshView.OnFooterRefreshListener, PullToRefreshView.OnHeaderRefreshListener, View.OnClickListener {


    var updatedialog: AlertDialog? = null
    lateinit var P: IYuLiaoPrintP
    lateinit var adapter: YuliaoPrintAdapter
    lateinit var yuliaolist: MutableList<YuliaoPrintBean>
    lateinit var sousuobean: SousuoBean
    var mc_ids: MutableList<String> = java.util.ArrayList()
    var mc_names: MutableList<String> = java.util.ArrayList()

    var dayinBean = YuliaoPrintBean()
    override fun getLayoutId(): Int {
        return R.layout.fragmengt_yuliao_print
    }

    override fun initData() {
        sousuobean = SousuoBean()
        yuliaolist = ArrayList()
        adapter = YuliaoPrintAdapter(yuliaolist, activity!!)
        P = IYuLiaoPrintP(yuliaolist, this, activity!!)
        LvYuliaoPrint.adapter = adapter
        LvYuliaoPrint.onItemClickListener = this
        btGuolv.setOnClickListener(this)
        atWuLiaoLeiBie.setOnClickListener { atWuLiaoLeiBie.showDropDown() }
        tvStartTime.text = Myutil.getjulidate2(-1)
        tvEndTime.text = Myutil.getjulidate2(1)
        val listsp = ArrayList<String>()
        listsp.add("全部")
        listsp.add("已标记")
        listsp.add("未标记")
        val sadapter = ArrayAdapter(activity, R.layout.lv_sp_tvitem, listsp)
        spState.adapter = sadapter
        tvStartTime.setOnClickListener(this)
        tvEndTime.setOnClickListener(this)
        btGuolv.setOnClickListener(this)
        ivShezhi.setOnClickListener(this)
        Pull.setheader(true)
        Pull.setOnFooterRefreshListener(this)
        Pull.setOnHeaderRefreshListener(this)
        P.getcategory()
        var ly = sp.getString("lanya","")
        if(ly != null && ly != ""){
            lanya = ly;
        }

    }

    private fun getData() {
        sousuobean.color_color_mh = etColor.text.toString()
        sousuobean.start_time = tvStartTime.text.toString()
        sousuobean.end_time = tvEndTime.text.toString()
        sousuobean.mb_area_num = etQuhao.text.toString()
        sousuobean.width = etwidth.text.toString()
        sousuobean.height = etheight.text.toString()
        if (mc_names.contains(atWuLiaoLeiBie.text.toString())) {
            mc_names.indices
                    .filter { mc_names[it] == atWuLiaoLeiBie.text.toString() }
                    .forEach { sousuobean.mc_id = mc_ids[it] }
        }
        if (sousuobean.mc_id == "") {
            Myutil.MyTost("物料类别必选")
            return
        }
        if (sousuobean.mb_area_num == "") {
            Myutil.MyTost("区号必须填写")
            return
        }
        sousuobean.isbiaoji = spState.selectedItem.toString()
        sousuobean.time_category = "mb.productive_time"
        updatedialog = Myutil.showupdatedialog(activity, "正在查询", false)
        P.sousuo(sousuobean)
    }

    override fun onClick(p0: View?) {
        when (p0) {
            btGuolv -> {
                getData()
            }
            tvStartTime -> {
                Dialogutil.showBottoPopupWindow(tvStartTime, "选择开始时间", tvStartTime.text.toString(), activity)
                Myutil.notjianpan(context, btGuolv)
            }
            tvEndTime -> {
                Dialogutil.showBottoPopupWindow(tvEndTime, "选择结束时间", tvEndTime.text.toString(), activity)
                Myutil.notjianpan(context, btGuolv)
            }
            ivShezhi -> {
                var c = context;
                if(c != null){
                    val dialog = AlertDialog.Builder(c).create()
                    dialog.setView(EditText(context))
                    dialog.show()
                    dialog.setContentView(R.layout.dialog_lanya_shezhi1)
                    val LanYaAdapter = ArrayAdapter(context, R.layout.lv_sp_tvitem, Myutil.ly_names())
                    dialog.SpLanYa.adapter = LanYaAdapter
                    dialog.SpLanYa.setSelection(LanYaUtil.ly_id(lanya))
                    val window = dialog.window
                    val p = window?.attributes // 获取对话框当前的参数值
                    p?.width = (sp.getInt("width", 0) * 0.9).toInt() // 宽度设置为屏幕的0.65
                    window?.attributes = p
                    dialog.LeftBt.setOnClickListener {
                        lanya = LanYaUtil.ly_address(dialog.SpLanYa.selectedItem.toString())
                        editor.putString("lanya", lanya)
                        editor.commit()
                        Myutil.MyTost("打印机切换成功")
                    }
                    dialog.RightBt.setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }
        }
    }

    companion object {
        var bean = YuliaoPrintBean()
        var lanya  = "34:81:F4:CB:1D:11"
//        var lanya  = "34:81:F4:CB:1D:11"
//        var lanya2 = "34:81:F4:CB:F3:D7"
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        Log.d("onItemClick","position"+position)
//        dayinBean = yuliaolist[position]
        bean = yuliaolist[position]
        if(bean.kailiao_time == ""){
            val intent = Intent(activity, DayinYuliaoActivity::class.java)
            startActivity(intent)
        }else{
            var c = context
            if(c != null){
                val dialog = AlertDialog.Builder(c)
                dialog.setTitle("提示")
                dialog.setMessage("确定要再次打印这个标签吗")
                dialog.setPositiveButton("确定") { dialog, which ->
                    val handle = @SuppressLint("HandlerLeak")
                    object : Handler() {
                        override fun handleMessage(msg: Message?) {
                            msg.let {
                                updatedialog?.dismiss()
                            }
                        }
                    }
                    updatedialog = Myutil.showupdatedialog(activity, "正在打印标签", false)
                    val thread = object : Thread() {
                        override fun run() {
                            dayin(yuliaolist[position],handle)
                        }
                    }
                    thread.start()
                }
                dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
                dialog.show()
            }

        }
    }


    fun qingkong() {
        if (isFirstLoad) {
            return
        }
        Pull.headerRefreshing()
    }

    override fun xialaOk() {
        updatedialog?.dismiss()
        Pull?.onHeaderRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun xialaNo() {
        updatedialog?.dismiss()
        Pull?.onHeaderRefreshComplete()
    }

    override fun shanglaOk() {
        updatedialog?.dismiss()
        Pull?.onFooterRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun shanglaNo() {
        updatedialog?.dismiss()
        Pull?.onFooterRefreshComplete()
    }

    override fun gainDataOk() {
        adapter.notifyDataSetChanged()
    }

    override fun onFooterRefresh(view: PullToRefreshView) {
        P.shangla()
    }

    override fun onHeaderRefresh(view: PullToRefreshView) {
        P.xiala()
    }

    override fun getcategoryOk(mc_ids: MutableList<String>, mc_names: MutableList<String>) {
        this.mc_ids = mc_ids;
        this.mc_names = mc_names;
        val av = ArrayAdapter(activity, android.R.layout.simple_dropdown_item_1line, this.mc_names)
        atWuLiaoLeiBie.setAdapter(av)
        if (mc_ids.contains("1")) {
            mc_ids.indices
                    .filter { mc_ids[it] == "1" }
                    .forEach { atWuLiaoLeiBie.setText(mc_names[it]) }
        }

        getData();
    }

    override fun getcategoryNo() {
    }

    fun dayin(bean : YuliaoPrintBean,handler: Handler){

        var tscActivity = TSCActivity()

        tscActivity.openport(FragmengtYuliaoPrintLabel.lanya);
        Myutil.Mylog("TAAG",FragmengtYuliaoPrintLabel.lanya)
        tscActivity.setup(110, 40, 3, 4, 0, 2, 0);
        tscActivity.clearbuffer();

//        tscActivity.printerfont(0,0,"32*48",0,1,1,bean.mcode)
        tscActivity.sendcommand("PUTBMP 10,10,\"logtsc.BMP\"")
//        tscActivity.sendcommand("PUTBMP 720,10,\"logo_tsc.BMP\"")
        tscActivity.sendcommand("\n");

        tscActivity.sendcommand("QRCODE " + 10 + "," + 80 + ",H,7,A,0,M2,S7,\"" + bean.mcode + "\"");
        tscActivity.sendcommand("\n");


        tscActivity.sendcommand("QRCODE " + 950 + "," + 200 + ",H,7,A,0,M2,S7,\"" + bean.mcode+","+bean.color_code + "\"");
        tscActivity.sendcommand("\n");
        tscActivity.sendcommand("PUTBMP 800,150,\"yuanyuan.BMP\"")
        tscActivity.sendcommand("\n");

        val typeface = Typeface.createFromAsset(Myapp.getContext().assets, "宋体-粗体.ttf")

        tscActivity.windowsfont(250, 20, 0, 60, typeface, bean.m_name);

        tscActivity.windowsfont(600, 20, 0, 60, typeface, bean.mb_batch+",")

        tscActivity.windowsfont(1100, 20, 0, 60, typeface, bean.mb_area_num );

        tscActivity.windowsfont(250, 80, 0, 50, typeface, "开料：" + bean.m_size)

        tscActivity.windowsfont(750, 80, 0, 50, typeface, "成品："+bean.finished_size)

        tscActivity.windowsfont(250, 150, 0, 40, typeface, "颜色："+bean.color_color)

        tscActivity.windowsfont(250, 220, 0, 50, typeface, "封边："+bean.es_type+",")

        tscActivity.windowsfont(815, 185, 0, 50, typeface, bean.ban_jian_hao)

        tscActivity.windowsfont(20, 280, 0, 40, typeface, Myutil.getdata1(bean.mb_productive_time));

        tscActivity.windowsfont(400, 280, 0, 50, typeface, bean.mm_menjiaokong)


        tscActivity.windowsfont(20, 340, 0, 50, typeface, "备注："+bean.m_remark)

        tscActivity.windowsfont(20, 410, 0, 50, typeface, "开槽："+bean.slot_name)
        tscActivity.windowsfont(370, 410, 0, 50, typeface, bean.weihao+",")
        tscActivity.windowsfont(460, 410, 0, 50, typeface, bean.mcode+",")
        tscActivity.windowsfont(1100, 410, 0, 50, typeface, bean.es_dnum_mark+",")

        Thread.sleep(2000);
        tscActivity.printlabel(1, bean.m_counts.toInt());
        tscActivity.closeport()
        val msg = Message.obtain()
        msg.obj = "信息"
        handler.sendMessage(msg)
    }

    class SousuoBean {
        var isbiaoji = ""
        var mc_id = ""
        var color_color_mh = ""
        var mb_area_num = ""
        var time_category = ""
        var start_time = ""
        var end_time = ""
        var width = ""
        var height = ""
    }
}